//
//  UIViewController+HDLockHomeController.m
//  app
//
//  Created by pro on 2017/4/11.
//  Copyright © 2017年 hdaren. All rights reserved.
//

#import "HDLockHomeController.h"
#import "HDAppDelegate.h"
#import "HDLockHomeView.h"
#import "HDJihuoController.h"
#import "HDLockManger.h"
#import "HDJihuoController.h"
#import "GattManager.h"
#import "QRCodeGenerator.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface HDLockHomeController ()<HDLockHomeViewDelegate,GattBLEDelegate>
{
    HDLockHomeView * home_view;
    NSArray *keys;
}
@property (nonatomic,strong)HDLockManger * manger;
@property (nonatomic,strong)HDLockRequset * login_request;
@property (nonatomic,strong)HDMiyaoRequset * miyao_reqeust;
@property (nonatomic,strong)HDErWeiMaRequset * erweima_request;
@property (nonatomic,strong)NSMutableArray * key_array;
@property (nonatomic,strong)NSString * key_str;
@property (nonatomic,strong)NSDictionary * erweima_dic;

@property(strong,nonatomic) GattManager *gattManager;

@property(nonatomic,assign) BOOL jihuo_bool;

@end

@implementation  HDLockHomeController

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"开门";
    
//    [UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
//    // 并让自己成为第一响应者
//    [self becomeFirstResponder];
    
    
    self.manger = [HDLockManger shareManager];
    self.login_request = [[HDLockRequset alloc]initWithTarget:self action:@selector(loginResult:)];
    self.miyao_reqeust = [[HDMiyaoRequset alloc]initWithTarget:self action:@selector(miyaoResult:)];
    self.erweima_request = [[HDErWeiMaRequset alloc]initWithTarget:self action:@selector(erweimaResutl:)];
    self.key_array = [NSMutableArray array];
    
    
    
    //
    //此处增加sdk
    //
    ///创建BLE搜索对象
    self.gattManager = [[GattManager alloc] init];
    self.gattManager.delegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(BLEmonitor:) name:@"BLENotification" object:nil];
    
    
    
    
    home_view = [[HDLockHomeView alloc]initWithFrame:CGRectMake(0, 64, UBO_SCREEN.width, UBO_SCREEN.height-64-49)];
    home_view.delegate = self;
    [self.view addSubview:home_view];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshErCode) name:@"refreshErcode" object:nil];
    
    
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    
    /*
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"linglingID"]length] > 0 && [[[NSUserDefaults standardUserDefaults]objectForKey:@"erweima_key"]count] > 0) {
        
        
        
    }else
    {
        [home_view.lock_home_btn setBackgroundImage:[UIImage imageNamed:@"video_recorder_start_btn_activate"] forState:UIControlStateNormal];
        
        home_view.bottom_lab.text = @"如您小区安装有手机开门设备，请联系物业索取二维码";
        
     //   self.jihuo_bool = NO;
        //登录
        //        [self getLogin];
        //直接跳转
    //    HDJihuoController * jihuo = [[HDJihuoController alloc]init];
    //    jihuo.hidesBottomBarWhenPushed = YES;
    //    [self.navigationController pushViewController:jihuo animated:YES];
        
        
   //     __weak typeof(self) wself = self;
   //     jihuo.JIhuoblockJump = ^(){
            
  //          [wself getLogin];
            
  //      };
        
  //      jihuo.DenglublockJump = ^(){
            
   //         [wself getMIyao];
            
  //      };

        
        
    
    }
    */
    
    
}




//激活
-(void)jihuoFounction
{
    [MyToast showWithText:@"敬请期待"];
    
    
    /*
    HDJihuoController * jihuo_vc = [[HDJihuoController alloc]init];
    jihuo_vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:jihuo_vc animated:YES];
    
    __weak typeof(self) wself = self;
    jihuo_vc.JIhuoblockJump = ^(){
        
         [wself getLogin];
        
    };
    
    jihuo_vc.DenglublockJump = ^(){
        
        [wself getMIyao];
        
    };
     */
    
}

//开锁
-(void)lockHomeFounction
{
    /*
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"linglingID"]length] > 0) {
        
        //已激活过
        self.jihuo_bool = YES;
        
        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"erweima_key"]count] > 0) {
            
            //直接开门
            home_view.lock_home_btn.enabled = NO;
            //进行开门操作
            [self lockDoor];
            
        }else
        {
            //获取秘钥在开门
            //获取秘钥
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [self getMIyao];
        }
        
        
        
        
        
    }else
    {
        self.jihuo_bool = NO;
        //登录
//        [self getLogin];
        //直接跳转
        HDJihuoController * jihuo = [[HDJihuoController alloc]init];
        jihuo.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:jihuo animated:YES];
        
        
        __weak typeof(self) wself = self;
        jihuo.JIhuoblockJump = ^(){
            
            [wself getLogin];
            
        };
        
        jihuo.DenglublockJump = ^(){
            
            [wself getMIyao];
            
        };

        
    }
     */
}


-(void)refreshErCode
{
    self.jihuo_bool = NO;
    //获取秘钥，刷新二维码
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self getMIyao];
}


- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    NSLog(@"开始摇动");
    
    [MyToast showDefaultBottonWithText:@"开始摇动"];
    
    
    
    //return;
}

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    NSLog(@"取消摇动");
    [MyToast showDefaultBottonWithText:@"取消摇动"];
   // return;
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.subtype == UIEventSubtypeMotionShake) { // 判断是否是摇动结束
        NSLog(@"摇动结束");
        [MyToast showDefaultBottonWithText:@"摇动结束"];
        
        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"linglingID"]length] > 0) {
            
            //已激活过
            self.jihuo_bool = YES;
            
            if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"erweima_key"]count] > 0) {
                
                //直接开门
                //进行开门操作
                [self lockDoor];
                
            }else
            {
                //获取秘钥在开门
                //获取秘钥
                [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                [self getMIyao];
            }
            
            
            
            
            
        }else
        {
            self.jihuo_bool = NO;
            //登录
            //        [self getLogin];
            //直接跳转
            HDJihuoController * jihuo = [[HDJihuoController alloc]init];
            jihuo.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:jihuo animated:YES];
            
            
            __weak typeof(self) wself = self;
            jihuo.JIhuoblockJump = ^(){
                
                [wself getLogin];
                
            };
            
            jihuo.DenglublockJump = ^(){
                
                [wself getMIyao];
                
            };
            
            
        }
        
    }  
   // return;
}

//访客
-(void)fangkeFounction
{
    
}



-(void)getMIyao
{
    
    [home_view.lock_home_btn setBackgroundImage:[UIImage imageNamed:@"video_recorder_start_btn_open"] forState:UIControlStateNormal];
    
    
    home_view.bottom_lab.text = @"告诉你一个秘密手机摇一摇也可以开门哦！本二维码可在10分钟使用3次，您再次进入系统会重新生成!";
    
    NSDictionary * params = @{@"phone":[[NSUserDefaults standardUserDefaults]objectForKey:@"lock_phone"]};
    
    [self.manger getMIyaoRequest:self.miyao_reqeust Params:params];
    
}
-(void)miyaoResult:(HDMiyaoRequset*)rt
{
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    
    if (rt.success) {
//        [MyToast showDefaultBottonWithText:rt.msg];
        
        //获取二维码
        DLog(@"erweima:%@",rt.pushDic);
        NSArray * array = [rt.pushDic arrayForKey:@"result"];
        if (array.count > 0) {
            
            if (self.key_array.count > 0) {
                [(NSMutableArray*)self.key_array removeAllObjects];
//                [self.key_array removeAllObjects];
            }
            
            DLog(@"key_class ==  %@",self.key_array.class);

            
            for (int i = 0 ; i < array.count; i++) {
                NSDictionary * temp = [array objectAtIndex:i];
                NSString * key = [temp objectForKey:@"key"];
                [self.key_array addObject:key];
                
            }
            
            
//            NSDictionary * temp = [array objectAtIndex:0];
//            
//            self.key_str = [temp objectForKey:@"key"];
////
//            [[NSUserDefaults standardUserDefaults]setObject:self.key_str forKey:@"erweima_key"];
            [[NSUserDefaults standardUserDefaults]setObject:self.key_array forKey:@"erweima_key"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            
            
            if (self.jihuo_bool == NO) {
                //从激活页面跳转回来
                //只显示二维码图片
//                keys = @[self.key_str];
                NSString *qrCode = [self.gattManager createElevatorControllQRWithLLingId:[[NSUserDefaults standardUserDefaults]objectForKey:@"linglingID"] Keys:self.key_array ValidTime:10 ValidNum:3 AuthLevel:0 EncryptKey:@"12345678"];
                DLog(@"qrcode===== %@",qrCode);
                home_view.er_code_iv.image = [QRCodeGenerator qrImageForString:qrCode imageSize:home_view.er_code_iv.bounds.size.width];
            }else
            {
                //进行开门操作
                [self lockDoor];
            }
            
            
//            [self getErweima];
            //  [self lockDoor];
            
        }else
        {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            [MyToast showDefaultBottonWithText:@"很抱歉，没有搜索到有用密钥，无法正常开门"];
            home_view.bottom_lab.text = @"您的开门权限未开通,请联系物业";
            
            
        }
        
        

        
    }
    else if (rt.status == 1){
        //清除key 和令令id
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"erweima_key"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"linglingID"];
        
        
        [home_view.lock_home_btn setBackgroundImage:[UIImage imageNamed:@"video_recorder_start_btn_activate"] forState:UIControlStateNormal];
        
        home_view.bottom_lab.text = @"如您小区安装有手机开门设备，请联系物业索取二维码";
        
    
    }
    else
    {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        [MyToast showDefaultBottonWithText:rt.msg];
        
    }
    
    
}



-(void)getLogin
{
    

    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:KEY_CHAIN_UDID,@"phone_sn",[[NSUserDefaults standardUserDefaults]objectForKey:@"lock_phone"],@"phone",[[NSUserDefaults standardUserDefaults]objectForKey:@"lock_code"],@"code", nil];
    
    [self.manger loginRequst:self.login_request Params:params];
    
    
}
-(void)loginResult:(HDLockRequset*)rt
{
    
    
    if (rt.success) {
//        DLog(@"linglingID = %@",rt.pushDic);
        [MyToast showDefaultBottonWithText:rt.msg];
        [[NSUserDefaults standardUserDefaults]setObject:rt.pushDic[@"result"] forKey:@"linglingID"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        
        
        [home_view.lock_home_btn setBackgroundImage:[UIImage imageNamed:@"video_recorder_start_btn_open"] forState:UIControlStateNormal];
        
        home_view.bottom_lab.text = @"告诉你一个秘密手机摇一摇也可以开门哦！本二维码可在10分钟使用3次，您再次进入系统会重新生成!";
        
        [self getMIyao];
        
        
        
    }else
    {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MyToast showDefaultBottonWithText:rt.msg];
//        //跳转
//        HDJihuoController * jihuo = [[HDJihuoController alloc]init];
//        jihuo.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:jihuo animated:YES];
//        
//        
//        __weak typeof(self) wself = self;
//        jihuo.JIhuoblockJump = ^(){
//            
//            [wself getLogin];
//            
//        };
//        
//        jihuo.DenglublockJump = ^(){
//            
//            [wself getMIyao];
//            
//        };
        
        
    }
    
    
    
}


-(void)getErweima
{

    NSDictionary * params = @{@"phone":[[NSUserDefaults standardUserDefaults]objectForKey:@"lock_phone"]};
    
    [self.manger getErWeiMaRequest:self.erweima_request Params:params];
    
    
}
-(void)erweimaResutl:(HDErWeiMaRequset*)rt
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    if (rt.success) {
        
        self.erweima_dic = rt.pushDic;
        [MyToast showDefaultBottonWithText:rt.msg];
        if (self.jihuo_bool == NO) {
            //从激活页面跳转回来
            //只显示二维码图片
//            keys = @[self.key_str];
            NSString *qrCode = [self.gattManager createElevatorControllQRWithLLingId:[[NSUserDefaults standardUserDefaults]objectForKey:@"linglingID"] Keys:self.key_array ValidTime:10 ValidNum:3 AuthLevel:0 EncryptKey:@"12345678"];
            home_view.er_code_iv.image = [QRCodeGenerator qrImageForString:qrCode imageSize:home_view.er_code_iv.bounds.size.width];
        }else
        {
            //进行开门操作
            [self lockDoor];
        }
        
        
        
        
        
        
    }else
    {
        [MyToast showDefaultBottonWithText:rt.msg];
    }
    

}

-(void)lockDoor
{
    //获取V2门禁二维码
   // NSString *key1 = [self getPathString:@"LLing" pathType:@"txt"];
    
    //更换二维码，
//    keys = @[self.key_str];
//    NSString *qrCode = [self.gattManager getQRCode:keys refreshInterval:180];
//    home_view.er_code_iv.image = [QRCodeGenerator qrImageForString:qrCode imageSize:home_view.er_code_iv.bounds.size.width];

    [self searchOpenDoor];
    
    
}

#pragma mark - 隔一定时间后如果还没得到回应就重新搜索
-(void)searchOpenDoor
{
    
    
 
   
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"erweima_key"]count] > 0){
        
        self.key_array = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults]objectForKey:@"erweima_key"]];
    
    }
    
     DLog(@"self.key_array == %@",self.key_array);
    
    [self.gattManager decode:self.key_array willOverdue:^(NSString *key){
        
        [MyToast showDefaultBottonWithText:@"key将要过期，还能使用"];
        //NSLog(@"key将要过期，还能使用，请从服务器获取全新的key: %@", key);
    } beenOverdue:^(NSString *key){
        
        [MyToast showDefaultBottonWithText:@"key已经过期，不能使用"];
        
       // NSLog(@"key已经过期，不能使用，请从服务器获取全新的key: %@", key);
    } allOverdue:^(NSArray *keyArray){
        
//        [MyToast showDefaultBottonWithText:@"所有的key已经过期，不能开门"];
        
        home_view.bottom_lab.text = @"您的开门权限已过期，请联系物业！";
        
      //  NSLog(@"所有的key已经过期，不能开门，请从服务器获取全新的keyArray: %@", keyArray);
    }];
    [self.gattManager setUp];//实例化中心角色
    [self.gattManager setFlagDefault];
    [self.gattManager scan:5];//整形参数为超时时间，当搜索时间到达预设时间则返回搜索超时。
    
   
    
    
}


#pragma mark - GattBLE Delegate
-(void)getBleSearchAnswer:(int)result resultString:(NSString *)str26
{
    switch (result) {
        case 0:
        {
            
            NSLog(@"开门成功");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"开门成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
            [MyToast showDefaultBottonWithText:@"开门成功"];
           // [showText setText:@"开门成功"];
            
            home_view.lock_home_btn.enabled = YES;
            
            break;
        }
        case 1:
        {
            NSLog(@"蓝牙未打开");
            [MyToast showDefaultBottonWithText:@"蓝牙未打开"];
            //[showText setText:@"蓝牙未打开"];
            home_view.lock_home_btn.enabled = YES;
            break;
        }
        case 2:
        {
            NSLog(@"搜索超时");
            [MyToast showDefaultBottonWithText:@"搜索超时"];
           // [showText setText:@"搜索超时"];
            home_view.lock_home_btn.enabled = YES;
            break;
        }
        case 3:
        {
            NSLog(@"开门超时");
            [MyToast showDefaultBottonWithText:@"开门超时"];
           // [showText setText:@"开门超时"];
            home_view.lock_home_btn.enabled = YES;
            break;
        }
            
        default:
        {
            NSLog(@"开门失败");
            [MyToast showDefaultBottonWithText:@"开门失败"];
            //[showText setText:@"开门失败"];
            home_view.lock_home_btn.enabled = YES;
            break;
        }
    }
    
    if(self.gattManager)
        [self.gattManager setFlagDefault];
    
}


-(void)BLEmonitor:(NSNotification *)notification{
    NSNumber *result = [notification object];
    NSLog(@"result = %@",result);
    switch ([result intValue]) {
        case 2:
        {
            NSLog(@"未搜索到设备");
            [MyToast showDefaultBottonWithText:@"未搜索到设备"];
           // [showText setText:@"未搜索到设备"];
            break;
        }
        case 3:
        {
            NSLog(@"正在连接设备");
            [MyToast showDefaultBottonWithText:@"正在连接设备"];
           // [showText setText:@"正在连接设备"];
            break;
        }
        case 4:
        {
            NSLog(@"连接成功");
            [MyToast showDefaultBottonWithText:@"连接成功"];
          //  [showText setText:@"连接成功"];
            break;
        }
        case 5:
        {
            NSLog(@"连接超时");
            [MyToast showDefaultBottonWithText:@"连接超时"];
           // [showText setText:@"连接超时"];
            break;
        }
        case 6:
        {
            NSLog(@"连接失败");
            [MyToast showDefaultBottonWithText:@"连接失败"];
         //   [showText setText:@"连接失败"];
            break;
        }
        case 7:
        {
            NSLog(@"未找到服务或特性");
            [MyToast showDefaultBottonWithText:@"未找到服务或特性"];
            //[showText setText:@"未找到服务或特性"];
            break;
        }
            
            
        default:
            break;
    }
}




@end
